package com.heima.search.service.impl;

import cn.hutool.core.util.IdUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 异步保存搜索记录
     * @param keyword 搜索关键词
     * @param userId 用户id
     */
    @Async("taskExecutor")
    @Override
    public void insert(String keyword, Integer userId) {

        //1.查询搜索记录
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)
                .and("keyword").is(keyword)), ApUserSearch.class);

        //2.搜索记录不存在：保存搜索记录
        if(apUserSearch==null){
            apUserSearch = new ApUserSearch();
            apUserSearch.setId(IdUtil.getSnowflake(0,0).nextId());
            apUserSearch.setUserId(userId);
            apUserSearch.setKeyword(keyword);
            apUserSearch.setIsDeleted(0); //未删除
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setUpdatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3.搜索记录存在，状态未删除：更新updatedTime
        if(apUserSearch.getIsDeleted()==0){
            apUserSearch.setUpdatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //4.搜索记录存在，状态已删除：更新isDeleted为0且更新updatedTime
        apUserSearch.setIsDeleted(0); //未删除
        apUserSearch.setUpdatedTime(new Date());
        mongoTemplate.save(apUserSearch);
    }

    @Override
    public ResponseResult findUserSearch() {

        Query query = Query.query(Criteria.where("userId").is(ThreadLocalUtil.getUserId()).and("isDeleted").is(0));
        query.with(Sort.by(Sort.Direction.DESC, "updatedTime"));
        query.limit(10);

        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(apUserSearchList);
    }


    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //1.判断搜索记录是否存在
        ApUserSearch apUserSearch = mongoTemplate.findById(dto.getId(), ApUserSearch.class);
        if(apUserSearch==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "搜索记录不存在无法删除");
        }

        //2.判断是否重复删除
        if(apUserSearch.getIsDeleted()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "无需重复删除");
        }

        //3.修改isDeleted=1且修改updatedTime
        apUserSearch.setIsDeleted(1);
        apUserSearch.setUpdatedTime(new Date());
        mongoTemplate.save(apUserSearch);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
